package com.jwater.core.net;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

import com.jwater.core.common.S;

import jwater.org.apache.mina.core.buffer.IoBuffer;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class CallPacket implements Serializable {
	private static final long serialVersionUID = 34462938191158914L;

	private int methodLen;
	private byte[] method;
	private int argsLen;
	private byte[] args;

	public byte[] serialize() throws Exception {
		IoBuffer ioBuffer = IoBuffer.allocate(8 + methodLen + argsLen);
		ioBuffer.putInt(methodLen);
		ioBuffer.put(method);
		ioBuffer.putInt(argsLen);
		if (argsLen > 0) {
			ioBuffer.put(args);
		}
		return ioBuffer.array();
	}

	public CallPacket deserialize(byte[] data) throws Exception {
		IoBuffer ioBuffer = IoBuffer.allocate(data.length);
		ioBuffer.put(data);
		ioBuffer.flip();
		methodLen = ioBuffer.getInt();
		byte[] temp = new byte[methodLen];
		ioBuffer.get(temp);
		method = temp;
		argsLen = ioBuffer.getInt();
		if (argsLen > 0) {
			temp = new byte[argsLen];
			ioBuffer.get(temp);
			args = temp;
		}
		return this;
	}

	public int getMethodLen() {
		return methodLen;
	}

	public void setMethodLen(int methodLen) {
		this.methodLen = methodLen;
	}

	public String getMethod() {
		try {
			return new String(method, 0, methodLen, S.charset);
		} catch (UnsupportedEncodingException e) {
			throw new NetException("charset error", e);
		}
	}

	public void setMethod(byte[] method) {
		this.method = method;
	}

	public int getArgsLen() {
		return argsLen;
	}

	public void setArgsLen(int argsLen) {
		this.argsLen = argsLen;
	}

	public byte[] getArgs() {
		return args;
	}

	public void setArgs(byte[] args) {
		this.args = args;
	}

	@Override
	public String toString() {
		return "CallPacket [methodLen=" + methodLen + ", method=" + method + ", argsLen=" + argsLen + "]";
	}
}
